﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Xtee.Core.Services
{
    public class CertificateLocator
    {
        public static X509Certificate2 Locate(string thumbprint)
        {
            X509Certificate2 certificate = null;

            foreach (var storeName in new[] {StoreName.My })
            {
                foreach (var storeLocation in new[] {StoreLocation.CurrentUser, StoreLocation.LocalMachine})
                {
                    var store=new X509Store(storeName,storeLocation);
                    store.Open(OpenFlags.ReadOnly);

                    certificate =store.Certificates.Cast<X509Certificate2>()
                        .FirstOrDefault(
                            x => !string.IsNullOrEmpty(x.Thumbprint) && x.Thumbprint.Equals(thumbprint.Replace(" ", ""), StringComparison.InvariantCultureIgnoreCase));

                    if (certificate != null)
                        break;
                    
                }

                if (certificate != null)
                    break;
            }

            if (certificate == null)
                throw new Exception($"Couldn't locate certificate for thumbprint {thumbprint}. Places looked Current User/Local Machine Personal store.");
            

            return certificate;
        }
    }
}
